package com.common.service.impl;

import com.common.domain.entity.LoginUser;
import com.common.domain.entity.ResponseResult;
import com.common.domain.entity.User;
import com.common.service.AdminService;
import com.common.util.JwtUtil;
import com.common.util.RedisCache;
import com.common.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author
 * @Date 2023/10/26 20:40
 **/
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    public static final String REDIS_ADMIN_PRE = "adminlogin:";
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());


        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //判断认证是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //获取用户的userid,生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(String.valueOf(userId));
        //把用户信息存在redis缓存中
        redisCache.setCacheObject(REDIS_ADMIN_PRE +userId, loginUser);
        //把token和userInfo封装返回

        Map<String,String> jwtMap = new HashMap<>();
        jwtMap.put("token", jwt);
        return  ResponseResult.okResult(jwtMap);
    }

    @Override
    public ResponseResult logout() {
        Long userId = SecurityUtils.getUserId();

        redisCache.deleteObject(REDIS_ADMIN_PRE + userId);

        return ResponseResult.okResult();
    }
}
